package Controller;

import java.sql.SQLException;


import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.Session;
import org.zkoss.zk.ui.Sessions;
import org.zkoss.zk.ui.WrongValueException;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zul.Div;
import org.zkoss.zul.Label;
import org.zkoss.zul.Textbox;
import org.zkoss.zul.Window;


import databaseHelper.UserDAO;
import datatypes.User;
/**
 * Login Controller
 * 
 * java counterpart of the Login page. Determines whether login is correct
 * 
 * @author Rupert
 *
 */
public class LoginController extends SelectorComposer<Window> {
	
	private UserDAO userDAO;
	
	@Wire
	private Textbox nameTxb, passTxb;
	
	@Wire
	private Label validLogin;
	
	@Listen("onClick=#confirmButton")
	public void confirm(){
		doLogin();
	}
	

	@Listen("onClick=#registerButton")
	public void register(){
		   Executions.sendRedirect("/registration.zul");
	}
	
	boolean doLogin(){
		userDAO = new UserDAO();
		User loggedUser = new User(nameTxb.getValue(), passTxb.getValue());
		try {
			userDAO.verifyLogin(loggedUser);
		} catch (SQLException e) {
			validLogin.setStyle("color: red; float:left;");
			validLogin.setValue("Login failed!"); 
			e.printStackTrace();
			return false;
		} 
		validLogin.setStyle("color: green; float:left;");
		validLogin.setValue("Login correct!"); 
		Session session =  Sessions.getCurrent();
		session.setAttribute(UserCredentialManager.KEY_USER_Model, new UserCredentialManager(loggedUser.getName()));
		Executions.sendRedirect("dashboard.zul");
		return true;
	}
	
	
	public void doBeforeComposeChildren(Window comp) throws Exception{
		super.doBeforeComposeChildren(comp);
		
		
		System.out.println("TEEEEEESTTTTTTTTTTTTTTTTTTTTTTT");
		
		Session session = Executions.getCurrent().getSession();	
		if(UserCredentialManager.getInstance(session).isAuthenticated()){
			System.out.println("SCHON EINGELOGGT!");
			Executions.sendRedirect("dashboard.zul");
		}
	}


}
